package contest1607;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;

public class J {
    static Scanner cin = new Scanner(new BufferedInputStream(System.in));//大量输入优化版本
    static PrintWriter cout = new PrintWriter(new BufferedOutputStream(System.out));//大量输出优化版本
    static PrintWriter cerr = new PrintWriter(System.err, true);//开启调试模式,一般输出量不大，不需要buffered


    public static void main(String[] args) {
        //TODO AOJ开启你的ACM传奇人生
        cerr.println("----Start your ACM legendary life with AOJ(www.webturing.com)----");
        int m = cin.nextInt();
        int n = cin.nextInt();
        String[] D = new String[n];
        for (int i = 0; i < D.length; i++) {
            D[i] = cin.next();
        }
        Arrays.sort(D, new Comparator<String>() {
            int revOrder(String s) {
                int cnt = 0;
                for (int x = 0; x < s.length() - 1; x++)
                    for (int y = x + 1; y < s.length(); y++)
                        if (s.charAt(x) > s.charAt(y))
                            ++cnt;
                return cnt;
            }

            @Override
            public int compare(String a, String b) {
                return revOrder(a) - revOrder(b);
            }
        });
        for (String d : D) {
            cout.println(d);
        }
        cin.close();//关闭输入流
        cout.close();//关闭输出流，这是必须的，否则一般不会自动刷新缓冲区
    }
}

